﻿using GMap.NET;
using GMap.NET.Projections;
using GMap.NET.WindowsForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMap.Test
{
   public class ArrowOverlay : GMapOverlay
   {
      private GMapControl MapControl { get; set; }

      private List<Arrow> Arrows;

      MercatorProjection projection = new GMap.NET.Projections.MercatorProjection();


      public void Add(Arrow arrow)
      {
         if (!Arrows.Contains(arrow))
         {
            Arrows.Add(arrow);
         }
      }

      public void Remove(Arrow arrow)
      {
         if (Arrows.Contains(arrow))
         {
            Arrows.Remove(arrow);
         }
      }

      public void RemoveAll()
      {
         Arrows.Clear();
      }

      public ArrowOverlay(string name, GMapControl mapControl)
      {
         Arrows = new List<Arrow>();
         MapControl = mapControl;
      }

      public override void OnRender(Graphics g)
      {
         base.OnRender(g);
         int oX = -MapControl.Width / 2;
         int oY = -MapControl.Height / 2;
         int offsetX = (int)g.ClipBounds.X - oX;
         int offsetY = (int)g.ClipBounds.Y - oY;
         foreach (var arrow in Arrows)
         {
            if (arrow.Visable)
            {
               GPoint start = projection.FromLatLngToPixel(arrow.Start, (int)MapControl.Zoom);
               GPoint end = projection.FromLatLngToPixel(arrow.End, (int)MapControl.Zoom);

               GPoint mapPosition = MapControl.PositionPixel;

               PointF startPoint = new PointF(start.X - mapPosition.X + offsetX, start.Y - mapPosition.Y + offsetY);
               PointF endPoint = new PointF(end.X - mapPosition.X + offsetX, end.Y - mapPosition.Y + offsetY);

               AdjustableArrowCap lineCap = new AdjustableArrowCap(9, 9, true);   //设置一个线头	
               lineCap.Filled = true;
               lineCap.MiddleInset = 3.1f; //设置箭头中间的缩进
               Pen pen = new Pen(Brushes.Red, 5);
               //pen.CustomStartCap = new AdjustableArrowCap(5, 20, true);
               pen.CustomEndCap = (CustomLineCap)lineCap;

               g.SmoothingMode = SmoothingMode.AntiAlias;
               g.DrawLine(pen, startPoint, endPoint);
            }
            
         }
      }
   }

   /// <summary>
   /// 箭头
   /// </summary>
   public class Arrow
   {
      public Arrow(PointLatLng start, PointLatLng end)
      {
         Start = start;
         End = end;
         Visable = true;
      }

      /// <summary>
      /// 是否可见
      /// </summary>
      public bool Visable
      {
         get;
         set;
      }

      /// <summary>
      /// 起点
      /// </summary>
      public PointLatLng Start
      {
         get;
         set;
      }

      /// <summary>
      /// 终点
      /// </summary>
      public PointLatLng End
      {
         get;
         set;
      }
   }
}
